<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@ page errorPage="pagerro.jsp"%>
<%@ page import="opbanco.Banco"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.ResultSet"%>
<%
//Não faz cache
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", -1); //evita o caching no servidor proxy
//Caso não esteja logado, vá para o índex
if (session.getAttribute("cod_usuario") == null) { response.sendRedirect("index.jsp"); }
Connection cx;
%>
<html>
<head>
<title>SisProc</title>
<link rel="stylesheet" href="img/Estilo.css" type="text/css" />
<style>
    select {
        width:300px;
    }
</style>
<script>
function Validacao(f){
    if  (w('sel').length == 0)  {
        alert('Selecione os processos!');
      	f.lst_processodisp.options[0].selected = true;
        f.lst_processodisp.focus();
      	return;
    }
    if (confirm("Confirma cancelamento do tramite?")) {
        //Seleciona todos os itens na lista
        for (var i=0;i < w('sel').length;i++) {
                w('sel').options[i].selected = true;
        }
        if (confirm("Apaga o despacho desse tramite ?")) {
            f.action = 'canlote.jsp?ad=1';
        } else {
            f.action = 'canlote.jsp?ad=0';
        }
        f.submit();
    }
}
function Todos(f) {
    if (!confirm("Seleciona todos?")) {
        return;
    }
    if  (f.lst_processodisp.length != 0)  {
        for (var i=0;i < f.lst_processodisp.length;i++) {
            f.lst_processodisp.options[i].selected = true;
            SelProcesso('disp','sel');
            i--;
        }
    }
}
function w(x){
    return document.getElementById(x);
}
function SelProcesso(one,two) {
    one = w(one);
    two = w(two);
    var oneSelected = one.selectedIndex;
    var twoLength   = two.length;
    if(oneSelected == -1) {
        window.alert('Selecione na lista');
	return;
    }
    var existe = false;
    for (var i=0;i < two.length;i++) {
        if (two.options[i].text == one.options[oneSelected].text) {
            existe=true;
            i=two.length;
        }
    }
    if (!existe) {
        two.options[twoLength] = new Option(one.options[oneSelected].text,one.options[oneSelected].value);
        one.options[oneSelected] = null;
        document.getElementById('txt_protocolo').value = "";
        document.getElementById('txt_protocolo').focus();
    }
}
function pesquisa(valor,e) {
    var whichCode;
    if (!e) var e = window.event;
    if (e.keyCode) whichCode = e.keyCode;
    else if (e.which) whichCode = e.which;
    if( (whichCode >= 33 && whichCode <= 126) || whichCode == 8) {
        url="ajax.jsp?tipo=canlote&parm=" + valor;
        ajax(url);
    }
}
function ajax(url) {
    req = null;
    req = newXMLHttpRequest();
    if (req) {
        req.onreadystatechange = processa;
	req.open('GET',url,true);
	req.send(null);
    }
}
function processa() {
    if (req.readyState == 4) { // apenas quando o estado for "completado"
        if (req.status ==200) { // apenas se o servidor retornar "OK"
            document.getElementById('prot').innerHTML = req.responseText;
            //document.getElementById('prot').style.visibility = 'visible';
        } else {
            alert("Não foi possível obter os Protocolos:\n" + req.statusText);
	}
    }
}
function newXMLHttpRequest() {
    var xmlreq = false;
    if (window.XMLHttpRequest) {
        xmlreq = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                // Unable to create an XMLHttpRequest with ActiveX
            }
        }
    }
    return xmlreq;
}
</script>
</head>
<body>
<%
    if (request.getParameter("ad") == null) {
%>
<%@ include file="Top.inc" %>
<center>
    <strong>Cancelamento de tramite em lote</strong>
    <hr width="80%" size="3">
    <form method="post" name="form" action="canlote.jsp">
        <table border="0" width="530">
            <tr align="center">
              <td>Possíveis:</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
            </tr>
            <tr align="center">
              <td><input id="txt_protocolo" type="text" onKeyUp="pesquisa(this.value,event);" class="num" style="width:300px"></td>
              <td>&nbsp;</td>
              <td><font color="blue">Selecionados:</font></td>
            </tr>
            <tr align="center"><td><div id="prot"><select id="disp" size="16" style="width:300px" ondblclick="SelProcesso('disp','sel')">
<%
    cx = Banco.Conecta(getServletContext().getRealPath("/") + "/bd_sisproc.jsp");
    ResultSet pt = null;
    ResultSet rs = Banco.Consulta("SELECT DISTINCT Tb_Tramite.Protocolo FROM Tb_Tramite INNER JOIN Tb_Processo ON Tb_Tramite.Protocolo="+
    "Tb_Processo.Protocolo WHERE (Tb_Processo.Cd_Status=1) AND (Tb_Tramite.Cd_SetorOrigem=" + session.getAttribute("cod_setor").toString() +
    ") AND (apensado is null) ORDER BY Tb_Tramite.Protocolo",cx);
    while (rs.next()) {
        pt = Banco.Consulta("SELECT TOP 1 Tb_Tramite.Cd_Tramite,Tb_Tramite.Protocolo,setor.des_resumo,Tb_Tramite.cd_setororigem FROM Tb_Tramite INNER JOIN tb_setor setor ON " +
             "Tb_Tramite.Cd_SetorDestino=setor.cod_setor WHERE (Tb_Tramite.Protocolo='" + rs.getString("protocolo") + "') ORDER BY Tb_Tramite.Cd_Tramite DESC",cx);
        pt.next();
        if (pt.getString("Cd_SetorOrigem").equals(session.getAttribute("cod_setor"))) {
            out.print("<option value='" + pt.getString("cd_tramite") + "'>" + Banco.Protoc(pt.getString("Protocolo")) + " - " + pt.getString("des_resumo")+ "</option>");
        }
    }
%>
          </select></div></td>
          <td><p><input type="button" value="Todos" onClick="Todos(this.form)"></td>
          <td><select name="lst_processosel[]" size="16" id="sel" multiple style="width: 300px" ondblclick="SelProcesso('sel','disp')"></select></td>
	</tr>
<tr align="center">
  <td width="50%"><input type="button" value="&gt;&gt; Adicionar &gt;&gt;" onClick="SelProcesso('disp','sel')"></td>
  <td></td>
  <td width="50%"><input type="button" value="&lt;&lt; Remover &lt;&lt;" onClick="SelProcesso('sel','disp')"></td>
</tr>
</table><br>
    <p><input type="button" value="Enviar" onClick="Validacao(this.form)">
       <input type="button" value="Voltar" onClick="location.href='transito.jsp'">
       <input type="button" value="Indice" onClick="location.href='indice.jsp'"></p>
    </form>
</center>
<%@ include file="Bot.inc" %>
<%
    } else {
        cx = Banco.Conecta(getServletContext().getRealPath("/") + "/bd_sisproc.jsp");
        out.println("<Script language='JavaScript'>");
        String[] vetor = request.getParameterValues("lst_processosel[]");
        int w;
        int sucesso=0;
        for (int i=0;i < vetor.length;i++) {
            w=Banco.Can_Tram(vetor[i],session.getAttribute("cod_setor").toString(),session.getAttribute("cod_usuario").toString(),request.getParameter("ad"),cx);
            if (w==1) { sucesso++; }
        }
        out.println("alert('Realizado com sucesso o cancelamento de " + sucesso + " instrumentos.');");
        out.println("self.location='transito.jsp';");
        out.println("</Script>");
    }
%>
</body>
</html>
